package com.example.lib_net.text_retrofit

import android.annotation.SuppressLint
import retrofit2.http.GET
import retrofit2.http.Query
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy

class RetrofitDemo2 {
    fun <T> create(service:Class<T>):T {
        val handler = object : InvocationHandler {
            @SuppressLint("NewApi")
            override fun invoke(p0: Any?, p1: Method?, p2: Array<out Any>?): Any? {
                //method:被代理的方法
                //args:被代理的方法的参数
                var url = ""
                var query = ""
                p1?.annotations?.forEach { annotation ->
                    when (annotation) {
                        is GET -> {
                            //获取注解的参数
                            url = annotation.value
                            println("url:$url")
                        }
                    }
                }
                p1?.parameters?.forEach { parameter ->
                    println("name: ${parameter.name}")
                    println("type: ${parameter.type}")
                    parameter.annotations?.forEach { annotation ->
                        when (annotation) {
                            is Query -> {
                                query = annotation.value
                                println("Query: ${annotation.value}")
                            }
                        }
                    }
                }
                println("args:$p2")
                //构建request对象
                //args 实参
                return p1!!.invoke(this, p2)
            }
        }
            return Proxy.newProxyInstance(
                service.classLoader,
                arrayOf(service),
                handler) as T
        }
    }